import { IObj } from '../interface'

function filter(menus: IObj[], parent_no: string, id: string, item: IObj) {
	const sub_id = item[id]
	const chil = menus.filter((sub) => {
		return sub[parent_no] === sub_id
	})
	if (chil.length > 0) {
		return {
			...item,
			children: chil.map((c) => {
				return filter(menus, parent_no, id, c)
			})
		}
	} else {
		return item
	}
}

export default function tree(menus: IObj[], parent_no: string, id: string) {
	const M = new Map()
	return menus.map((item) => {
		M.set(item[id], item)
		return item
	}).filter((item) => {
		return !M.get(item[parent_no])
	}).map((item) => {
		return filter(menus, parent_no, id, item)
	})
}
